import { deleteAssets, getAssets } from '@/services/ant-design-pro/api';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Drawer, message } from 'antd';
import React, { useCallback, useRef, useState, useEffect } from 'react';
import CreateForm from './components/CreateForm';
import EditForm from './components/EditForm';
import { fetchAssetsData } from '../../../utility/fetchcategoryforselect';
const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.AssetsListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.AssetsListItem[]>([]);
  const [assetsclass, setAssetsClass] = useState<{ [key: string]: { text: string } }>({});
  const [assetsname, setAssetsName] = useState<{ [key: string]: { text: string } }>({});
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  const [messageApi, contextHolder] = message.useMessage();

  // 抽取格式化函数，统一功能，转成valueEnum的格式
  const formatValueEnum = (data: any[]) => {
    return data.reduce((acc, item) => {
      acc[item.value] = { text: item.label };
      return acc;
    }, {} as { [key: string]: { text: string } });
  };

  useEffect(() => {
    const loadData = async () => {
      // 获取两个类别的数据  1为资产类别，7为资产名称类别
      const [assetsclassdata, assetnamedata] = await Promise.all([
        fetchAssetsData(1),
        fetchAssetsData(7),
      ]);

      // 更新状态  
      setAssetsClass(formatValueEnum(assetsclassdata));
      setAssetsName(formatValueEnum(assetnamedata));
    };
    loadData();
  }, []);
  /*
  const { run: delRun, loading } = useRequest(...): 这里使用了解构赋值。
run: 这是 useRequest 返回的一个函数，用于触发请求。
delRun: 这是将 run 重命名为 delRun，以便更清楚地表示这是一个用于删除操作的函数。
loading: 这是一个布尔值，指示请求是否正在进行中。你可以使用这个值来显示加载状态（例如，禁用按钮或显示加载指示器）。
  */
  const { run: delRun, loading } = useRequest(deleteAssets, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('物资删除成功');
    },
    onError: () => {
      messageApi.error('物资删除失败');
    },
  });

  const columns: ProColumns<API.AssetsListItem>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.assets.class"
          defaultMessage="assets class"
        />
      ),
      dataIndex: 'assetsclass',
      valueEnum: assetsclass
    },
    {
      title: <FormattedMessage id="pages.assets.name" defaultMessage="assetsname" />,
      dataIndex: 'assetsname',
      valueEnum: assetsname
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.sn"
          defaultMessage="assetssn"
        />
      ),
      dataIndex: 'sn',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },

    },
    {
      title: <FormattedMessage id="pages.assets.number" defaultMessage="assetsnumber" />,
      dataIndex: 'assetsnumber',
      //hideInForm: true,

    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.type"
          defaultMessage="assetstype"
        />
      ),
      dataIndex: 'type',
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.storagetime"
          defaultMessage="storagetime"
        />
      ),
      dataIndex: 'time',
      valueType: 'date',
      sorter: true,
      search: false,//不开启查询功能
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.calinterval"
          defaultMessage="calinterval"
        />
      ),
      dataIndex: 'calinterval',
      sorter: true,
      search: false,//不开启查询功能
    },
    {
      title: (
        <FormattedMessage
          id="pages.assets.count"
          defaultMessage="count"
        />
      ),
      dataIndex: 'count',
      sorter: true,
      search: false,//不开启查询功能
    },
    //操作
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [

        <EditForm
          trigger={
            <a>
              <FormattedMessage id="pages.edit" defaultMessage="edit" />
            </a>
          }
          key="edit"
          //这个不是提交的函数，而是修改后重新渲染表单的函数
          onOk={actionRef.current?.reload}

          values={record}
        />,
      ],
    },
  ];

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = useCallback(
    async (selectedRows: API.AssetsListItem[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');

        return;
      }
      await delRun(selectedRows.map((row) => row.key));
    },
    [delRun],
  );

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.AssetsListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.assets.title',
          defaultMessage: '固定资产表',
        })}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [<CreateForm key="create" reload={actionRef.current?.reload} />]}
        request={getAssets}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              {/* <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre + item.count!, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span> */}
            </div>
          }
        >
          <Button
            type="primary"
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          {/* <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button> */}
        </FooterToolbar>
      )}
      {/* 这是点击sn号出现的物品详细说明抽屉页面 */}
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.sn && (
          <ProDescriptions<API.AssetsListItem>
            column={2}
            title={currentRow?.sn}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.sn,
            }}
            columns={columns as ProDescriptionsItemProps<API.AssetsListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
